package com.gs.disk.modules.headImgAndWallper.service.admin;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gs.entity.GeneralPage;
import com.gs.common.util.SQLUtils;
import com.gs.disk.modules.headImgAndWallper.dao.admin.AdminCategoryDao;
import com.gs.disk.modules.headImgAndWallper.entity.CategoryEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AdminCategoryService {

    @Resource
    private AdminCategoryDao dao;

    /**
     *
     * @param categoryName
     * @param page
     * @param limit
     * @return
     */
    public GeneralPage<CategoryEntity> list(String categoryName, Long page, Long limit) {
        QueryWrapper<CategoryEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("pid,id,category_name,category_level,data_status,update_time,sort");
        if(ObjectUtil.isNotEmpty(categoryName)) {
            queryWrapper.eq("category_name", categoryName);
        }
        queryWrapper.eq("category_level", 1);
        queryWrapper.orderByAsc("sort");

        GeneralPage<CategoryEntity> dto = SQLUtils.toPageSql(dao, queryWrapper, page, limit);

        List<CategoryEntity> records = dto.getList();

        records.forEach(e -> {
            QueryWrapper<CategoryEntity> wrapperChild = new QueryWrapper<>();
            wrapperChild.select("id,pid,category_name,category_level, data_status, update_time");
            wrapperChild.eq("category_level", 2);
            wrapperChild.eq("pid", e.getId());
            wrapperChild.orderByAsc("sort");
            List<CategoryEntity> categoryChildrenList = dao.selectList(wrapperChild);
            e.setChildren(categoryChildrenList);
        });
        return dto;
    }

    public void delete(Long id) {
        dao.deleteById(id);
    }

    public void save(CategoryEntity entity) {
        dao.insertOrUpdate(entity);
    }

    public CategoryEntity get(Long categoryId) {
        QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("id", categoryId);
        wrapper.select("id,pid,category_name,category_level, data_status, update_time");
        return dao.selectOne(wrapper);
    }
}
